package com.act;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bean.BaseBean;
import com.bean.UserInfo;
import com.bean.UserList;
import com.common.Constant;
import com.common.TextHttpResponseHandler;
import com.mUI.XListView;
import com.mUI.XListView.IXListViewListener;
import com.xike.kyt.R;
import com.xike.util.MyUtil;

public class Mine_FocusUsersAct extends BaseAct {

	TextView tv_back;
	XListView listView;
	MyAdapter adapter;

	UserList userList;
	ArrayList<UserInfo> users = new ArrayList<UserInfo>();

	ArrayList<Long> cancelFocusIds = new ArrayList<Long>();

	boolean isRefresh = false;
	int pageCursor = 1;
	boolean isLoadingMore = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_mine_focus_users);
		initViews();
	}

	@Override
	protected void initViews() {

		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);
		tv_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		listView = (XListView) findViewById(R.id.mineFocusUsers_listView);
		listView.setPullRefreshEnable(true);
		listView.setPullLoadEnable(true);
		listView.setAutoLoadEnable(true);

		adapter = new MyAdapter();
		listView.setAdapter(adapter);

		listView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pageCursor = 1;
				isRefresh = true;
				serviceGetFocusUsers();
			}

			@Override
			public void onLoadMore() {
				pageCursor++;
				isLoadingMore = true;
				serviceGetFocusUsers();
			}
		});

		serviceGetFocusUsers();

	}

	@Override
	protected void updateViews() {
		ArrayList<UserInfo> loadUsers = userList.getUsers();
		if (loadUsers != null && loadUsers.size() > 0) {

			if (isRefresh) {
				users.clear();
				users.addAll(loadUsers);
				adapter.notifyDataSetChanged();
				isRefresh = false;
				listView.stopRefresh();
				listView.updateRefreshTime();
				listView.setPullLoadEnable(true);
			} else {
				users.addAll(loadUsers);
				adapter.notifyDataSetChanged();
				if (isLoadingMore) {
					listView.stopLoadMore();
				}
				if (userList.getNext_cursor() > 0) {
					listView.showFooterView();
				} else {
					listView.setPullLoadEnable(false);
				}
			}

		}
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// if (position == 1) {
				// startActivityForResult(new Intent(Mine_FocusUsersAct.this, Friend_NewAct.class), REQUEST_CODE_TO_NEWFRIEND);
				// } else {
				// Friend friend = users.get(position - listView.getHeaderViewsCount());
				// Intent it_chat = new Intent(Mine_FocusUsersAct.this, ChatAct.class);
				// it_chat.putExtra("userId", friend.getIm_name());
				// it_chat.putExtra("userName", friend.getNick_name());
				// startActivity(it_chat);
				// }

			}
		});
	}

	private void serviceGetFocusUsers() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("page_cursor", String.valueOf(pageCursor)));
		params.add(new BasicNameValuePair("page_count", String.valueOf(Constant.LIST_PAGESIZE)));


		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_MINE_FOCUS_USERS, params);
		// // 本地缓存
		// if (LocalFileHelper.getInstance(this).fileIsExited(strUrl) && !isRefresh) {
		// FriendList result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), FriendList.class);
		// dealRequestResult(result);
		// return;
		// }

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				UserList result = gson.fromJson(responseString, UserList.class);
				dealRequestResult(result);

			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				if (isRefresh) {
					listView.stopRefresh();
				}
				mToast.showToast(Mine_FocusUsersAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(UserList result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				userList = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
				if (isRefresh) {
					listView.stopRefresh();
				}
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
			if (isRefresh) {
				listView.stopRefresh();
			}
		}
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return users.size();
		}

		@Override
		public UserInfo getItem(int position) {
			return users.get(position);
		}

		@Override
		public long getItemId(int position) {
			return users.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			UserInfo user = getItem(position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(Mine_FocusUsersAct.this).inflate(R.layout.listitem_mine_focus_users, null);
				holder.tv_name = (TextView) convertView.findViewById(R.id.lvitem_mineFocusUsers_tv_name);
				holder.tv_summary = (TextView) convertView.findViewById(R.id.lvitem_mineFocusUsers_tv_desc);
				holder.img_avator = (ImageView) convertView.findViewById(R.id.lvitem_mineFocusUsers_img_avator);
				holder.tv_status = (TextView) convertView.findViewById(R.id.lvitem_mineFocusUsers_tv_status);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			MyUtil.setTextViewText(holder.tv_name, user.getName(), 0, "未知用户");
			MyUtil.setTextViewText(holder.tv_summary, user.getSummary(), View.INVISIBLE, "");
			BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
			MyUtil.displayImageView(Mine_FocusUsersAct.this, user.getAvator(), holder.img_avator, bd.getBitmap(), false);

			holder.tv_status.setTag(user.getId());
			if (cancelFocusIds.contains(user.getId())) {
				holder.tv_status.setText("关注");
				holder.tv_status.setBackgroundResource(R.drawable.corner_06bf04);
				holder.tv_status.setTextColor(Color.parseColor("#ffffff"));
			} else {
				holder.tv_status.setText("取消关注");
				holder.tv_status.setBackgroundResource(R.drawable.corner_dfdfdd_fcfcfc);
				holder.tv_status.setTextColor(Color.parseColor("#999999"));
			}
			holder.tv_status.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					long userId = (Long) v.getTag();
					if (cancelFocusIds.contains(userId)) {// 关注
						serviceFocusUser(userId);
					} else {
						serviceCancelFocusUser(userId);
					}
				}
			});

			return convertView;
		}

		class ViewHolder {
			TextView tv_name;
			TextView tv_summary;
			ImageView img_avator;
			TextView tv_status;
		}

	}

	private void serviceFocusUser(final long userId) {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("user_id", String.valueOf(userId)));
		params.add(new BasicNameValuePair("page_cursor", String.valueOf(pageCursor)));
		params.add(new BasicNameValuePair("page_count", String.valueOf(Constant.LIST_PAGESIZE)));
		
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_USER_FOCUS, params);
		// 网络请求
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Mine_FocusUsersAct.this, "关注成功");
					cancelFocusIds.remove(userId);
					adapter.notifyDataSetChanged();
				} else {
					mToast.showToast(Mine_FocusUsersAct.this, getResources().getString(R.string.net_error));
				}

				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Mine_FocusUsersAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void serviceCancelFocusUser(final long userId) {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("user_id", String.valueOf(userId)));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_USER_CANCEL_FOCUS, params);
		// 网络请求
		client.delete(strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Mine_FocusUsersAct.this, "取消关注成功");
					cancelFocusIds.add(userId);
					adapter.notifyDataSetChanged();
				} else {
					mToast.showToast(Mine_FocusUsersAct.this, getResources().getString(R.string.net_error));
				}

				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Mine_FocusUsersAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

}
